package com.application.chiettinhdienluc.ui;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.DanhMucHoSoAdapter;
import com.application.chiettinhdienluc.adapter.DanhMucHoSoAdapter.ViewHolder;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.ChietTinhDataSource;
import com.application.chiettinhdienluc.db.HinhAnhChiTietDataSource;
import com.application.chiettinhdienluc.db.NhanCongChiTietDataSource;
import com.application.chiettinhdienluc.db.VatTuChiTietDataSource;
import com.application.chiettinhdienluc.dialog.ConfirmDialog;
import com.application.chiettinhdienluc.model.ChietTinhModel;
import com.application.chiettinhdienluc.model.HinhAnhChiTietModel;
import com.application.chiettinhdienluc.model.NhanCongChiTietModel;
import com.application.chiettinhdienluc.model.VatTuChiTietModel;
import com.application.chiettinhdienluc.rsclient.DataConnDetector;
import com.application.chiettinhdienluc.rsclient.HitCheckTask;
import com.application.chiettinhdienluc.rsclient.NetClientPost;
import com.application.chiettinhdienluc.rsclient.RsGetClient;
import com.application.chiettinhdienluc.utils.Log;
import com.application.chiettinhdienluc.utils.Utils;



public class DanhMucHsoActivity extends BaseActivity  {
	
	public DanhMucHsoActivity(int titleRes) {
		super(R.string.app_name);
	}
	
	public DanhMucHsoActivity() {
		super(R.string.app_name);
	}

	private final String TAG = DanhMucHsoActivity.class.getSimpleName();
	private ListView chiettinhListView;
	private ArrayList<ChietTinhModel> itemList = new ArrayList<ChietTinhModel>();
	private ArrayList<ChietTinhModel> itemListAll = new ArrayList<ChietTinhModel>();
	
	private String[] arrayFilterDanhMucHoSoAsNames;
	private int iFilterMode = 0;
	private AlertDialog mFilterModeDialog;
	private boolean runOnCreate = false;
	private HashMap<String, String> mapIdNameTrangThaiHoSo = new HashMap<String, String>();
	private DanhMucHoSoAdapter adapter;
	private ArrayList<String> idHoSoSelected = new ArrayList<String>();
	private ChietTinhDataSource dataSource = new ChietTinhDataSource();
	public final static int REQUEST_CODE_START_MAINTAB = 1000;
	String[] arrayTrangThaiHoSoName;
	Resources res;	
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();	
		if(!runOnCreate)
			loadChietTinhFollowMode(iFilterMode + 1);
		runOnCreate = false;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.danh_muc_hso_chiet_tinh_listview);
			
			
			HitCheckTask hitCheckTask = new HitCheckTask();
			hitCheckTask.execute();
			
			
			res = getResources();

			ActionBar actionbar = getSupportActionBar();

			if(actionbar != null)
			{
				actionbar.setTitle(res.getString(R.string.str_title_viewlist_chiettinh));
				actionbar.setDisplayHomeAsUpEnabled(true);
				actionbar.setDisplayShowHomeEnabled(true);
			}
			
			arrayFilterDanhMucHoSoAsNames = res.getStringArray(R.array.array_filter_danhmuc_hoso);
			if(arrayFilterDanhMucHoSoAsNames.length > 0)
				iFilterMode = arrayFilterDanhMucHoSoAsNames.length - 1;
			
			String[] arrayTrangThaiHoSoId = res.getStringArray(R.array.array_trangthaihoso_id);
			arrayTrangThaiHoSoName = res.getStringArray(R.array.array_trangthaihoso_name);
			
			for(int j = 0; j < arrayTrangThaiHoSoId.length; j++)
			{
				mapIdNameTrangThaiHoSo.put(arrayTrangThaiHoSoId[j], arrayTrangThaiHoSoName[j]);
			}
			
			chiettinhListView = (ListView)findViewById(R.id.chiettinhList);
//			chiettinhListView.setItemsCanFocus(true);
//			chiettinhListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//				@Override
//				public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
//					goToViewChietTinhDetail(pos);
//				}
//			});

//			progress_loading_view.setVisibility(View.VISIBLE);
//			new Thread(new Runnable() {
//				@Override
//				public void run() {
//					// TODO Auto-generated method stub
//				}
//			}, "LoadHoSoListTask").start();
			
//			loadChietTinh();
			if(itemListAll != null)
				itemListAll.clear();
			
			itemListAll = dataSource.loadChietTinh();
			itemList = new ArrayList<ChietTinhModel>(itemListAll);
			adapter = new DanhMucHoSoAdapter(this, itemList);
			chiettinhListView.setAdapter(adapter);
			
//			loadChietTinhAll();
			
			runOnCreate = true;
			if(idHoSoSelected != null) idHoSoSelected.clear();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}	

	private void loadChietTinhAll()
	{
		adapter.setItemList(itemList);
		adapter.notifyDataSetChanged();
		idHoSoSelected.clear();
	}
	
	private final int OPTIONMENU_MENU_MAIN	        = 0;
    private final int ID_ACTION_FILTER          	= OPTIONMENU_MENU_MAIN + 1;
    private final int ID_ACTION_DOWNLOAD     		= ID_ACTION_FILTER + 1;
    private final int ID_ACTION_SUBMIT     			= ID_ACTION_DOWNLOAD + 1;
    private final int ID_ACTION_DELETE         		= ID_ACTION_SUBMIT + 1;
    private final int ID_ACTION_REFRESH         	= ID_ACTION_DELETE + 1;

    private final short ORDER_POS_FIRST = 1;
    private final short ORDER_POS_SECOND = ORDER_POS_FIRST + 1;
    private final short ORDER_POS_THIRD = ORDER_POS_SECOND + 1;
    private final short ORDER_POS_FOURTH = ORDER_POS_THIRD + 1;
    private final short ORDER_POS_FIFTH = ORDER_POS_FOURTH + 1;
	
	@Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        if(res == null) return false;
        try {
            if(menu != null)
            {	menu.close();
            menu.clear();
            }
            
            //SubMenu submenu = menu.addSubMenu(OPTIONMENU_MENU_MAIN, OPTIONMENU_MENU_MAIN, ORDER_POS_FIFTH/*Menu.NONE*/, res.getString(R.string.main_tab_hint_btn_menu));
              

                          
            
            //submenu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_SUBMIT, Menu.NONE,
             //       res.getString(R.string.str_menu_submit))
             //       .setIcon(R.drawable.submit_icon)
             //       .setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);                    
            
            
            
           
            
            menu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_FILTER, ORDER_POS_SECOND,
                    res.getString(R.string.str_menu_filter))
                    .setIcon(R.drawable.filter_icon)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); 
            
            menu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_DOWNLOAD, ORDER_POS_THIRD,
                    res.getString(R.string.str_menu_download))
                    .setIcon(R.drawable.download_icon)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);     
            
            menu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_DELETE, ORDER_POS_FOURTH,
                    res.getString(R.string.str_menu_delete))
                    .setIcon(R.drawable.delete_icon)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            
            menu.add(OPTIONMENU_MENU_MAIN, ID_ACTION_REFRESH, ORDER_POS_FIFTH,
                    res.getString(R.string.str_menu_refresh))
                    .setIcon(R.drawable.refresh_icon)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);  
                   
            //MenuItem menuItem = submenu.getItem();
            //menuItem.setIcon(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
            //menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

            return true;
        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }
    }
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		menu.add(Menu.NONE, ID_ACTION_FILTER, Menu.NONE, R.string.str_menu_filter).setIcon(R.drawable.filter_icon).setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		menu.add(Menu.NONE, ID_ACTION_DOWNLOAD, Menu.NONE, R.string.str_menu_download).setIcon(R.drawable.download_icon).setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		menu.add(Menu.NONE, ID_ACTION_SUBMIT, Menu.NONE, R.string.str_menu_submit).setIcon(R.drawable.submit_icon).setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		menu.add(Menu.NONE, ID_ACTION_DELETE, Menu.NONE, R.string.str_menu_delete).setIcon(R.drawable.delete_icon).setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//		return true;
//	}
	
	private DataConnDetector detector; 
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int itemId = item.getItemId();
		switch (itemId) {
		case android.R.id.home:
			getSlidingMenu().toggle();
			break;
		case ID_ACTION_FILTER:
			filterDanhMucChietTinh();
			break;
		case ID_ACTION_DOWNLOAD:
			detector = new  DataConnDetector(MainApplication.getAppContext());
			if (detector.isConnectingToInternet()) {
			    getYauCauKhaoSat();
			}
			else
			{
				Toast.makeText(MainApplication.getAppContext(), R.string.no_connection_message, Toast.LENGTH_SHORT).show();
				//showDialog(R.string.no_connection_message);				
			}
			break;
			
		case ID_ACTION_SUBMIT:
			detector = new  DataConnDetector(MainApplication.getAppContext());
			if (detector.isConnectingToInternet()) {
				submitHoSoChietTinh();
			}
			else
			{
				Toast.makeText(MainApplication.getAppContext(), R.string.no_connection_message, Toast.LENGTH_SHORT).show();
				//showDialog(R.string.no_connection_message);				
			}		
			break;
		case ID_ACTION_DELETE:
			confirmDeleteHoSoChietTinh();
			break;	
		case ID_ACTION_REFRESH:
//			refreshHoSoChietTinh();
			refreshDataFromDB();
			break;
			
		}

		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onBackPressed() {
		finish();
	}
	
	private void filterDanhMucChietTinh() {
		showFilterDialog();
	}
	
	private void submitHoSoChietTinh() {
		try {
			 for(int i = 0; i <itemListAll.size(); i++)
			 {			
				 if(itemListAll.get(i).get_TrangThaiHoSo().equalsIgnoreCase("2") )
				 {
					RsSubmitTask task = new RsSubmitTask();
					task.execute(itemListAll.get(i));				
				 }
			 }
		}
		catch (Exception e) {
			e.printStackTrace();
			
		}		
	}
	
	private void confirmDeleteHoSoChietTinh(){
		if(itemList != null && itemList.size() > 0)
		{
//			int delete_count = 0;
//			for(int i = itemList.size() - 1; i >= 0; i--)
//			{
//				if(itemList.get(i).isCheckToDelete())
//				{					
//					delete_count += 1;
//				}
//			}
			
			int count = idHoSoSelected != null ? idHoSoSelected.size() : 0;
			
			if (count > 0)			
				showDeleteConfirmDialog(count);
			else
				return;
		}
	}
	
	private void showDeleteConfirmDialog(int delete_count) {		
		Dialog dialog = null;
		ConfirmDialog.ConfirmBuilder customBuilder = new ConfirmDialog.ConfirmBuilder(DanhMucHsoActivity.this);
		String msg = String.format(res.getString(R.string.str_delete_confirm), delete_count);

		customBuilder.setTitle(res.getString(R.string.str_thongBao))
		.setMessage(msg)
		.setNegativeButton(res.getString(R.string.str_no), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(dialog != null)
					dialog.dismiss();								
			}
		})
		.setPositiveButton(res.getString(R.string.str_yes), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(dialog != null)
					dialog.dismiss();
				if(DanhMucHsoActivity.this != null)
				{
					deleteHoSoChietTinh();
				}
			}
		});
		dialog = customBuilder.create();
		
		if(dialog != null) dialog.show();
	}
	
	private void deleteHoSoChietTinh() {
		VatTuChiTietDataSource vatTuDataSource = new VatTuChiTietDataSource();
		NhanCongChiTietDataSource nhanCongDataSource = new NhanCongChiTietDataSource();
		
		for(int i = itemList.size() - 1; i >= 0; i--)
		{
			if(itemList.get(i).isCheckToDelete())
			{
				int numRowHasEffect = dataSource.deleteItemByHoSoChietTinhId(String.valueOf(itemList.get(i).get_Id()));
				numRowHasEffect = vatTuDataSource.deleteItemByHoSoChietTinhId(String.valueOf(itemList.get(i).get_Id()));
				numRowHasEffect = nhanCongDataSource.deleteItemByHoSoChietTinhId(String.valueOf(itemList.get(i).get_Id()));
				
				itemList.remove(i);
			}
		}
		
		adapter.setItemList(itemList);
		adapter.notifyDataSetChanged();
		
		itemListAll = dataSource.loadChietTinh();
		idHoSoSelected.clear();
	}
	
	
	
	private void refreshHoSoChietTinh(){
		itemList.clear();
		itemList = new ArrayList<ChietTinhModel>(itemListAll);
		loadChietTinhAll();
	}
	
	
	private ProgressDialog progressBar ;
	
	private void getYauCauKhaoSat() {
		
		progressBar = new ProgressDialog(this);
		progressBar.setMessage(res.getString(R.string.str_yeucau_download_waiting));
		progressBar.setIndeterminate(true);
		progressBar.setCancelable(false);
		progressBar.show();
		
				
		try {
			
			 RsGetYauCauTask task = new RsGetYauCauTask();
		     task.execute();	
			
		}
		catch (Exception e) {
			e.printStackTrace();
			
		}
		
	}
	
	private String postResponse;
	
	private class RsSubmitTask extends AsyncTask<ChietTinhModel, Void, Bundle> {		   
        @Override
        protected Bundle doInBackground(ChietTinhModel...  ct) {
        	
        	String baseUrl = MainApplication.getServerURL();
        	//http://192.168.1.46:46685
        	String url = baseUrl + "/ctrs/resources/hosochiettinh";  
        	    		
    		NetClientPost poster = new NetClientPost(url);              
           	
			
    	
    		ct[0].set_ThongTinNha("");
    		
    		
    		
            postResponse = poster.submitHoSoKhachHang(ct[0]);
            
            String banCTinhId = postResponse.replaceAll(System.getProperty("line.separator"), " ").trim();
            
            Log.i("Ban Chiet Tinh ID", banCTinhId);
            Log.i("Ban Chiet Tinh ID size", "" + postResponse.length());
            
            
            ct[0].set_MaBanChietTinh(banCTinhId);
            
                   
            Log.i("Ket qua lam tron truoc khi submit", ct[0].get_LamTron() + "");
            
            poster.submitHoSoChietTinh(ct[0]);  
            
            VatTuChiTietDataSource vtdb = new VatTuChiTietDataSource();
            
            NhanCongChiTietDataSource ncdb = new NhanCongChiTietDataSource();
            
            ArrayList<VatTuChiTietModel> vattuList = vtdb.getSelectedVatTuByHoSoId(ct[0].get_Id());
            
            if(vattuList.size()>0) {
            	
               poster.submitChiTietVatTu(vattuList,banCTinhId );
               
            }
            
            ArrayList<NhanCongChiTietModel> nhancongList = ncdb.getSelectedNhanCongByHoSoId(ct[0].get_Id());
            if(nhancongList.size()>0) {
            	
               poster.submitChiTietNhanCong(nhancongList,banCTinhId );
               
            }
            
            HinhAnhChiTietDataSource haDataSource = new HinhAnhChiTietDataSource();
            
            ArrayList<HinhAnhChiTietModel> hinhanhList = haDataSource.getHinhAnhChiTietByHoSoId(ct[0].get_Id());
            
            if(hinhanhList.size()>0) {
            	
            	for(int i = 0; i <hinhanhList.size(); i++ ) {
            		
            		RsUploadImageTask uploadTask = new RsUploadImageTask();
            		uploadTask.execute(hinhanhList.get(i).getFilename(), ct[0].get_Id() + "", banCTinhId);
            		            		
            	}               
            }
             
			
			
            Bundle output = new Bundle();
            output.putLong("id", ct[0].get_Id());
            output.putString("banCTinhId", banCTinhId);
            return output;
        }
 
        
        String input; 
        
        @Override
        protected void onPostExecute(Bundle result) { 
        	Log.i(TAG, result.getString("banCTinhId"));        	
            Log.i("ban chiet tinh id", postResponse);
        	dataSource.updateTrangThaiHoSo(result.getLong("id"), result.getString("banCTinhId"));
        	
        	refreshDataFromDB();
        }
 
        @Override
        protected void onPreExecute() {
           // Log.i(TAG, "onPreExecute");
        	
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
            //Log.i(TAG, "onProgressInsert");
        }

	
 
    }
	
	
	
	
	JSONArray messages = null;
	JSONObject json = null;
	ArrayList<HashMap<String, String>> messageList = null;
	
	private class RsGetYauCauTask extends AsyncTask<String, Void, Void> {
		
		   
        @Override
        protected Void doInBackground(String... params) {
        	
            RsGetClient jParser = new RsGetClient();     
            //http://192.168.1.46:46685
            String baseUrl = MainApplication.getServerURL();
            String url = baseUrl + "/ctrs/resources/hosochiettinh/" + MainApplication.getMaDonViQuanLy();
            
            messages = jParser.getJSONFromUrl(url);  
         
            return null;
        }
 
        @Override
        protected void onPostExecute(Void result) {
          
        	//Log.i(TAG, messages.toString());
        	storeHoSoYeuCau();	   	
        	
        	
        }
 
        @Override
        protected void onPreExecute() {
           // Log.i(TAG, "onPreExecute");
           
        }
 
        @Override
        protected void onProgressUpdate(Void... values) {
            //Log.i(TAG, "onProgressInsert");
        }
 
    }
	
	protected void storeHoSoYeuCau()
	{
		try {           
        	                
            int j =1; 
            // looping through All Contacts
            for(int i = 0; i < messages.length(); i++){
            	
                JSONObject c = messages.getJSONObject(i);                
                
                ChietTinhModel ct = new ChietTinhModel();
                if(c.getString("tenKhang")!= null) {
                ct.set_MaYeuCauKhieuNai(c.getString("maYcauKnai") != null?c.getString("maYcauKnai"):"");             
                ct.set_TenKhachHang(c.getString("tenKhang"));     
                ct.set_DiaChi(c.getString("diaChi")!= null?c.getString("diaChi"):"");   
                
               
                
                String ngayND = "";
                
                if(c.getString("ngayNd") != null) {
                
	               	        		
	        		Date date = null;
	        		
	        		try {
	        			date = new SimpleDateFormat("yyyy-MM-dd").parse(c.getString("ngayNd"));
	        		} catch (java.text.ParseException e) {
	        			
	        			e.printStackTrace();
	        		} 	 
	        			
	        		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	        		ngayND = sdf.format(date);	
                }
                else
                {
                	ngayND = "";
                }
                
                ct.set_NgayND(ngayND);
                
                
                ct.set_DienThoaiDichVu(!c.getString("dthoaiDvu").equalsIgnoreCase("null")?c.getString("dthoaiDvu"):"");                 
                
                ct.set_DonViDauTu("0"); 
 
                boolean existed = false;
                
                existed = dataSource.checkHoSoExist(ct.get_TenKhachHang(), ct.get_ThongTinNha(), ct.get_MaYeuCauKhieuNai());
                
                if(!existed) {
                	long id = dataSource.insert(ct);              	
                	
                    ct.set_Id(id);
                    ct.set_TrangThaiHoSo("1");
                
                    itemList.add(0, ct);
                	adapter.setItemList(itemList);
            		adapter.notifyDataSetChanged();           		
            		
            		j++;
                }          
                
                }                    
                
                
            }        
            
            //refreshDataFromDB();
            
            progressBar.dismiss();
            
            Toast.makeText(MainApplication.getAppContext(),  res.getString(R.string.str_yeucau_download_finish), Toast.LENGTH_SHORT).show();
            
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
      
		
	}
	
	private void showFilterDialog() {

		final int N = arrayFilterDanhMucHoSoAsNames.length;

		if(iFilterMode < 0 || iFilterMode > N - 1)
		{
			iFilterMode = 0;
		}

		int[] icons = new int[N];
		List<Map<String, Object>> entries = new ArrayList<Map<String, Object>>();

		for(int i = 0; i < N; i++)
		{
			icons[i] = (i != iFilterMode) ? R.drawable.btn_radio_off_holo_light : R.drawable.btn_radio_on_holo_light;
			
			HashMap<String, Object> entry = new HashMap<String, Object>();
			entry.put("name", arrayFilterDanhMucHoSoAsNames[i]);
			entry.put("icon", icons[i]);
			entries.add(entry);
		}

		final SimpleAdapter a = new SimpleAdapter(
				this,
				entries,
				R.layout.filter_danhmuc_menu_item,
				new String[] {"name", "icon"},
				new int[] {R.id.tv_filter_mode_name, R.id.ic_choose_or_not});

		SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
			@Override
			public boolean setViewValue(View view, Object data, String textRepresentation) {
				if (view instanceof ImageView) {
					Drawable img = getResources().getDrawable((Integer)data);
					((ImageView)view).setImageDrawable(img);
					return true;
				}
				return false;
			}
		};

		a.setViewBinder(viewBinder);

		AlertDialog.Builder b = new AlertDialog.Builder(this);

		b.setTitle(getString(R.string.str_title_dlg_choose_filter_Mode));
		b.setCancelable(true);
//		b.setNegativeButton(res.getString(R.string.str_close), new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				if(dialog != null)
//					dialog.dismiss();
//			}
//		});

		b.setAdapter(a, new DialogInterface.OnClickListener() {
			@Override
			@SuppressWarnings("unchecked")
			public final void onClick(DialogInterface dialog, int which) {
				if(dialog != null)
					dialog.dismiss();
				
				//process
				iFilterMode = which;
				loadChietTinhFollowMode(iFilterMode + 1);
			}
		});

		mFilterModeDialog = b.create();

		if(mFilterModeDialog != null && !mFilterModeDialog.isShowing())
			mFilterModeDialog.show();
	}
	
	private void loadChietTinhFollowMode(int mode)
	{
		ChietTinhDataSource dataSource = new ChietTinhDataSource();
		
		if(mode == 1)//Phan cong khao sat
		{
			itemList.clear();
			itemList = dataSource.loadChietTinhOrderByNgayKS(mode);
			loadChietTinhAll();
		}	
		else if(mode == 2)//Hoan thanh khao sat
		{
			itemList.clear();
			itemList = dataSource.loadChietTinhOrderByNgayKS(mode);
			loadChietTinhAll();
		}
		else if(mode == 3) //Da gui ve cong ty
		{
			itemList.clear();
			itemList = dataSource.loadChietTinhOrderByNgayKS(mode);
			loadChietTinhAll();
		}
		else if(mode == 4)//Tat ca
		{
			itemList.clear();
			itemList = new ArrayList<ChietTinhModel>(itemListAll);
			loadChietTinhAll();
		}	
	}
	
	private int posLongClickSelected = -1;
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		try {
//			ViewHolder holder = (ViewHolder)((AdapterView.AdapterContextMenuInfo)menuInfo).targetView.getTag();
//			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
//			posLongClickSelected = info.position - (chiettinhListView.getHeaderViewsCount()); 
			ViewHolder holder = (ViewHolder)v.getTag();
			if(holder == null) return;
			posLongClickSelected = holder.position;
			
//			if(chatViewHelpers.chatAdapter != null && posLongClickSelected >= 0 && posLongClickSelected < chatViewHelpers.chatAdapter.getCount())
//			{
//				itemLongClickSelected = (ChatContent)chatViewHelpers.chatAdapter.getItem(posLongClickSelected);
//			}
//
//			if(itemLongClickSelected == null)
//				return;

			ChietTinhModel item = null;
			
			if(adapter != null && posLongClickSelected >= 0 && posLongClickSelected < adapter.getCount())
			{
				item = adapter.getItem(posLongClickSelected);
			}	
			
			String strHeaderCM = "";

			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
				View headerView = LayoutInflater.from(this).inflate(R.layout.context_menu_header, null);			
				((TextView)headerView.findViewById(R.id.tv_headertitleContextMenu)).setText(strHeaderCM);
				menu.setHeaderView(headerView);
			} else {
				menu.setHeaderTitle(strHeaderCM);
			}			

			if(menu != null)
			{
				menu.close();
				menu.clear();
			}

			getMenuInflater().inflate(R.menu.context_menu_danhmuc_hoso, menu);

			super.onCreateContextMenu(menu, v, menuInfo);
		} catch (Exception e) {
			Log.e(TAG, e.toString());
		}
	}
	
	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		try {
			int index = posLongClickSelected;

			//			if(index < 0 || index > chatViewHelpers.chatAdapter.getCount()) return false;
			//			Utils.showMess("Got click: " + item.toString() + " at index: " + index);

			if(item.getItemId()==R.id.context_menu_view) {

				goToViewChietTinhDetail(index);
			}
			else if (item.getItemId()==R.id.context_menu_submit)
			{		
				//				chatViewHelpers.deleteChatContent(index);			
			}
			
			
			return true;
		} catch (Exception e) {
			Log.e(TAG, e+"");
		}

		return false;
	}
	
	public void setCheckOrUnCheck(int pos, boolean check)
	{
		if(itemList != null && pos >= 0 && pos < itemList.size())
		{
			itemList.get(pos).setCheckToDelete(check);
			adapter.setItemList(itemList);
			adapter.notifyDataSetChanged();
			
			if(idHoSoSelected != null)
			{
				if(check)
				{
					if(!idHoSoSelected.contains(itemList.get(pos).get_Id() + ""))
						idHoSoSelected.add(itemList.get(pos).get_Id()+ "");
				}
				else
				{
					if(idHoSoSelected.contains(itemList.get(pos).get_Id() + ""))
						idHoSoSelected.remove(itemList.get(pos).get_Id() + "");
						
				}	
			}
		}
	}
	
	public String getTrangThaiHoSo(int pos)
	{
		return mapIdNameTrangThaiHoSo.containsKey(itemList.get(pos).get_TrangThaiHoSo()) ? mapIdNameTrangThaiHoSo.get(itemList.get(pos).get_TrangThaiHoSo()) : "";
	}
	
	public void goToViewChietTinhDetail(int pos)
	{
		try {
			if(adapter != null && pos >= 0 && pos < adapter.getCount())
			{
				GlobalData.SelectedNhanCongList.clear();
				GlobalData.SelectedVatTuList.clear();
				GlobalData.HinhAnhList.clear();
				GlobalData.globalChietTinh = adapter.getItem(pos);
				
				// get the current date
				final Calendar c = Calendar.getInstance();
				int mDay = c.get(Calendar.DAY_OF_MONTH);
				int mMonth = c.get(Calendar.MONTH) + 1;
				int mYear = c.get(Calendar.YEAR);	

				StringBuilder currentDate = new StringBuilder()								
				.append(mDay).append('/')
				.append(mMonth).append('/')
				.append(mYear).append(' ');

				if(TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayND()))
					GlobalData.globalChietTinh.set_NgayND(currentDate.toString().trim());

				if(TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayKhaoSat()))
					GlobalData.globalChietTinh.set_NgayKhaoSat(currentDate.toString().trim());

				if(TextUtils.isEmpty(GlobalData.globalChietTinh.get_NgayChietTinh()))
					GlobalData.globalChietTinh.set_NgayChietTinh(currentDate.toString().trim());

				
				String maNv = MainApplication.getNguoiDung().get_MaNVien();

				if(!TextUtils.isEmpty(maNv))
				{
					GlobalData.globalChietTinh.set_NhanVienKhaoSat(maNv);
					GlobalData.globalChietTinh.set_ThucHien(maNv);
				}

				// TODO Auto-generated method stub
				Intent localIntent = new Intent(DanhMucHsoActivity.this, com.application.chiettinhdienluc.ui.MainTabFragmentActivity.class);
				localIntent.putExtra(MainTabFragmentActivity.STR_EXTRA_IMODE, MainTabFragmentActivity.MODE_EDITABLE);
				startActivityForResult(localIntent, REQUEST_CODE_START_MAINTAB);
			}			
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void submitHoSo(int pos)
	{
		try {
			if(adapter != null && pos >= 0 && pos < adapter.getCount())
			{
				ChietTinhModel item = adapter.getItem(pos);
				if(item != null) {					
					detector = new  DataConnDetector(MainApplication.getAppContext());
					if (detector.isConnectingToInternet()) {
						RsSubmitTask task = new RsSubmitTask();
						task.execute(item);
						
						Utils.showMess(String.format(res.getString(R.string.str_submit_hoso_success), item.get_TenKhachHang()));
					}
					else
					{
						Toast.makeText(MainApplication.getAppContext(), R.string.no_connection_message, Toast.LENGTH_SHORT).show();
						//showDialog(R.string.no_connection_message);				
					}		
					
					
					
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void refreshDataFromDB()
	{
		if(itemListAll != null)
			itemListAll.clear();
		
		itemListAll = dataSource.loadChietTinh();
		itemList = new ArrayList<ChietTinhModel>(itemListAll);
		adapter = new DanhMucHoSoAdapter(this, itemList);
		chiettinhListView.setAdapter(adapter);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		// TODO Auto-generated method stub
		try {
			if(requestCode == REQUEST_CODE_START_MAINTAB && resultCode == RESULT_OK)
			{
				refreshDataFromDB();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

private class RsUploadImageTask extends AsyncTask<String, Void, Bundle> {		   
    @Override
    protected Bundle doInBackground(String...  ct) {
    	
    	String baseUrl = MainApplication.getServerURL();
    	//http://192.168.1.46:46685
    	String url = baseUrl + "/ctrs/resources/hosochiettinh";  
    	    		
		NetClientPost poster = new NetClientPost(url);       
       	
		String result = "fail";		
		
		result = poster.uploadHinhAnhHoSo(ct[0], ct[1], ct[2] );  
		
		Bundle output = new Bundle();
        output.putString("file_name", ct[0]);
        output.putString("result", result);
        return output;
        
        
       
    }

    
    String input; 
    
    @Override
    protected void onPostExecute(Bundle bundle) {   	        	
       
        
        String result = bundle.getString("result");
        
        Log.i("Upload result", result);
        
        if(result.equalsIgnoreCase("success")) {
        	
        	HinhAnhChiTietDataSource dataSource = new HinhAnhChiTietDataSource();
        	
        	dataSource.updateSumitted(bundle.getString("file_name"));
        	
        }
        	
    	
    }

    @Override
    protected void onPreExecute() {
       // Log.i(TAG, "onPreExecute");
    	
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        //Log.i(TAG, "onProgressInsert");
    }



}

}